const conn = require('../app/database')

class OrderModel {
	async createOrder(
		uid,
		outTradeNo,
		orderNo,
		payState,
		totalFee,
		addressId,
		goodsCartIds,
		goodsIds,
		goodsNums,
		goodsSkuDescs,
		goodsNameDesc,
		leaveMessage
	) {
		// order本身是SQL里边独有的关键字，所以，这里必须添加``，否则会报错！
		const statement = `
        INSERT INTO 
        dg_order (user_id, out_trade_no, order_no, pay_state,total_fee,address_id,goods_cart_ids, goods_ids, goods_nums, goods_sku_descs, goods_name_desc,leave_message) 
        VALUES (?,?,?,?,?,?,?,?,?,?,?,?); 
      `
		const [result] = await conn.execute(statement, [
			uid,
			outTradeNo,
			orderNo,
			payState,
			totalFee,
			addressId,
			goodsCartIds,
			goodsIds,
			goodsNums,
			goodsSkuDescs,
			goodsNameDesc,
			leaveMessage,
		])
		return result
	}

	async getOrderRecordByOrderId(orderId) {
		const statement = `SELECT o.id, o.order_no orderNo, o.pay_state payState FROM dg_order o WHERE id = ?;`
		const [result] = await conn.execute(statement, [orderId])
		return result
	}

	async updateOrderPayStateByOrderNo(uid, orderNo, payState) {
		const statement = `UPDATE dg_order SET pay_state=? WHERE user_id = ? AND order_no = ?;`
		const [result] = await conn.execute(statement, [payState, uid, orderNo])
		return result
	}

	async getOrderList(uid) {
		const statement = `
      SELECT
        o.id orderId, o.user_id userId, o.order_no orderNo, o.pay_state payState, o.total_fee totalFee, 
        o.address_id addressId, o.goods_cart_ids goodsCartIds, o.goods_ids goodsIds, o.goods_nums goodsNums,
        o.goods_sku_descs goodsSkuDescs, o.goods_name_desc goodsNameDesc, o.leave_message leaveMessage
      FROM dg_order o WHERE user_id = ?
      ORDER BY o.id DESC;
    `
		const [result] = await conn.execute(statement, [uid])
		return result
	}
}

module.exports = new OrderModel()
